package com.ocean.aws;

import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.Bukkit;
import com.ocean.aws.config.PluginConfig;
import org.bukkit.plugin.Plugin;
import com.ocean.aws.husksync.HuskSyncAdapter;
import com.ocean.aws.aw.AWBridge;
import com.ocean.aws.command.AWSyncCommand;
import net.william278.husksync.api.HuskSyncAPI;

public final class ArmourersWorkshopSync extends JavaPlugin {

    private HuskSyncAPI huskApi;
    private HuskSyncAdapter adapter;
    private AWBridge bridge;
    private java.util.concurrent.ScheduledExecutorService scheduler;

    @Override
    public void onEnable() {
        PluginConfig cfg = new PluginConfig(this);
        this.bridge = new AWBridge();
        Plugin huskSync = Bukkit.getPluginManager().getPlugin("HuskSync");
        boolean useHuskSync = cfg.huskSyncEnabled && huskSync != null && huskSync.isEnabled();

        if (useHuskSync && bridge != null) {
            this.huskApi = HuskSyncAPI.getInstance();
            this.adapter = new HuskSyncAdapter(this, this.bridge, cfg.compress, cfg);
            this.adapter.register();
            getLogger().info("检测到 HuskSync，将优先使用其玩家数据系统进行同步。");
        } else {
            if (huskSync == null || !huskSync.isEnabled()) {
                getLogger().severe("未检测到 HuskSync 或未启用。本插件需要 HuskSync 才能工作。");
            }
            if (this.bridge == null) {
                getLogger().severe("未检测到 Armourer's Workshop API。无法进行时装同步。");
            }
        }

        // 始终注册调试命令（HuskSync 模式也可使用 size 查看导出大小）
        if (this.bridge != null) {
            getCommand("aw-sync").setExecutor(new AWSyncCommand(this, this.bridge, cfg));
        }

        // 定时同步 world/skin-database/objects 与 Redis（可选）
        if (cfg.skinRelayEnabled && this.adapter != null && cfg.skinSyncPeriodSeconds > 0) {
            scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(r -> {
                Thread t = new Thread(r, "AW-SkinRelay-Sync");
                t.setDaemon(true);
                return t;
            });
            int period = Math.max(10, cfg.skinSyncPeriodSeconds);
            scheduler.scheduleAtFixedRate(() -> {
                try {
                    var relayField = com.ocean.aws.husksync.HuskSyncAdapter.class.getDeclaredField("relay");
                    relayField.setAccessible(true);
                    Object relay = relayField.get(this.adapter);
                    if (relay instanceof com.ocean.aws.relay.SkinRelay r) {
                        java.nio.file.Path objectsDir = java.nio.file.Paths.get("");
                        try {
                            var worlds = getServer().getWorlds();
                            java.io.File worldFolder = worlds.isEmpty() ? new java.io.File(getServer().getWorldContainer(), "world") : worlds.get(0).getWorldFolder();
                            objectsDir = worldFolder.toPath().resolve("skin-database").resolve("objects").normalize();
                        } catch (Throwable ignored) {}
                        int changed = r.syncObjectsDirectory(objectsDir);
                        if (changed > 0) {
                            getLogger().info("AW skinRelay periodic sync changed=" + changed + ", objectsDir=" + objectsDir);
                        }
                    }
                } catch (Throwable ignored) {}
            }, period, period, java.util.concurrent.TimeUnit.SECONDS);
        }
    }

    @Override
    public void onDisable() {
        if (scheduler != null) {
            try { scheduler.shutdownNow(); } catch (Throwable ignored) {}
        }
    }
}
